<?php


namespace App\Models;

use Illuminate\Database\Eloquent\Relations\HasOne;
use Mockery\Exception;

class Notice extends Base
{

    public $timestamps = FALSE;
    protected $table = 'estate_notice';
    protected $appends = ['community_name'];

    /**
     * 关联物业管理员
     * @return HasOne
     */
    public function one_estate(): HasOne
    {
        return $this->hasOne(AdminEstate::class, "id", "admin_user");
    }
    /**
     * 获取列表
     * @param null $where
     * @param string $whereRaw
     * @param string $order
     * @param string $sort
     * @param null $field
     * @param int $limit
     * @return mixed
     */
    public function getList($where = null, $whereRaw = '', $order = 'id', $sort = 'desc', $field = null, $limit = 15)
    {
        $model = self::where($where);
        if (isset($order)) {
            $model = $model->orderBy($order, $sort);
        }
        if ($whereRaw) {
            $model = $model->whereRaw($whereRaw);
        }

        return $model->select()->paginate($limit)->toArray();
    }


    // 添加
    public function create($data)
    {
        $data['create_time'] = time();
        $data['start_time'] = strtotime($data['start_time']);
        $data['end_time'] = strtotime($data['end_time']);
        return self::addInfo($data);
    }

    // 修改
    public function edit($data)
    {
        $data['create_time'] = strtotime($data['create_time']);
        $data['start_time'] = strtotime($data['start_time']);
        $data['end_time'] = strtotime($data['end_time']);
        return self::updateByWhere(['id' => $data['id']], $data);
    }

    // 删除
    public function deletes($ids)
    {
        $ids = explode(',', $ids);
        try {
            foreach ($ids as $key => $val) {
                self::delByWhere(['id' => $val]);
            }
            return true;
        } catch (Exception $exception) {
            return false;
        }
    }

    /**
     * 小区名称
     * @param $value
     * @return false|string
     */
    public function getCommunityNameAttribute()
    {
        $ids = explode(',', $this->attributes['community_id']);
        $name = Community::whereIn('community_id', $ids)->get('community_name')->toArray();
        $names = array_column($name, 'community_name');
        return implode(' | ', $names);
    }


    /**
     * 开始时间
     * @param $value
     * @return false|string
     */
    public function getStartTimeAttribute($value)
    {
        $value = $value ? date('Y-m-d', $value) : '';
        return $value;
    }


    /**
     * 结束时间
     * @param $value
     * @return false|string
     */
    public function getEndTimeAttribute($value)
    {
        $value = $value ? date('Y-m-d', $value) : '';
        return $value;
    }
}
